from redis import asyncio as aioredis
from config.config import get_settings


class RedisUtil:
    """
    Redis相关方法
    """

    @classmethod
    async def create_redis_pool(cls) -> aioredis.Redis:
        """
        应用启动时初始化redis连接
        :return: Redis连接对象
        """
        redis = await aioredis.from_url(
            url=get_settings().redis_url,
            username=get_settings().redis_username,
            password=get_settings().redis_pwd,
            db=get_settings().redis_db,
            encoding="utf-8",
            decode_responses=True
        )
        print("redis 链接成功")
        return redis

    @classmethod
    async def close_redis_pool(cls, app):
        """
        应用关闭时关闭redis连接
        :param app: fastapi对象
        :return:
        """
        await app.state.redis.close()

